<template>
  <div>
    <el-button type="success " @click="open">添加</el-button>
      <!-- 查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" style="display: inline-block; margin-left: 600px;">
        <el-form-item label="">
            <el-input v-model="formInline.empName" placeholder="员工姓名"></el-input>
        </el-form-item>
             <!-- 时间范围 -->
     <template>
        <div class="block" style="display: inline-block;">
            <el-date-picker
                v-model="formInline.time"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['12:00:00']">
            </el-date-picker>
        </div>
    </template>
     <!-- 时间范围 -->
    <el-form-item label="" style="display: inline-block;">
        <template>
            <el-select v-model="formInline.deptId" clearable  placeholder="所属部门">
                <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                </el-option>
            </el-select>
        </template>
    </el-form-item> 
    <el-form-item>
            <el-button type="primary" @click="sureSubmit">查询</el-button>
        </el-form-item>   
    </el-form>
      <!-- 查询 -->
     
      <el-table :data="empList" style="width: 100%">
        <el-table-column label="编号" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{scope.row.age}}</span>
          </template>
        </el-table-column>
        <el-table-column label="职位" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{scope.row.job}}</span>
          </template>
        </el-table-column>
        <el-table-column label="入职时间" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.entryDate|dateFilter}}</span>
          </template>
        </el-table-column>  
        <el-table-column label="薪资" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{scope.row.salary}}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属部门" width="180">
            <template slot-scope="scope">
            <span style="margin-left: 10px">{{scope.row.dept.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像" width="180">
            <template slot-scope="scope">
            <img :src="path+'imgs/'+scope.row.photo" width="120px"/>
          </template>
        </el-table-column>    
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small"  @click="handleEdit(scope.row)">编辑</el-button>
            &nbsp;
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>           
          </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block footer">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20,40]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="AllData">
    </el-pagination>
  </div>
    <!-- 模态框添加与修改操作 -->
    <el-dialog :title="tishi" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="form" label-width="80px">
  <el-form-item label="姓名">
    <el-input v-model="form.name"></el-input>
  </el-form-item>
  <el-form-item label="年龄">
    <el-input v-model="form.age"></el-input>
  </el-form-item>
  <el-form-item label="职位">
    <el-input v-model="form.job"></el-input>
  </el-form-item>
  <el-form-item label="薪资">
    <el-input v-model="form.salary"></el-input>
  </el-form-item>
  <el-form-item label="入职时间">
    <el-col :span="11">
      <el-date-picker type="date" placeholder="选择日期" v-model="form.entryDate" style="width: 100%;"></el-date-picker>
    </el-col>
  </el-form-item>
  <!-- 下拉框开始 -->
  <el-form-item label="所属部门">
    <template>
  <el-select v-model="form.deptId" placeholder="请选择">
    <el-option
      v-for="item in deptList"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
</template>
  </el-form-item>

<!-- 下拉框结束 -->
  <el-form-item label="图片">
    <div class="alert-box-item">
		<div class="bigImg-div" @click="toGetImg">
      <p v-if="!valueUrl" style="font-size: 16px; margin-left: 20px; margin-top: 50px;">点击添加照片</p>
			<img class="bigImg" :src=valueUrl v-if="valueUrl">
		</div>
	</div>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmit">{{tishi}}</el-button>
    <el-button @click="dialogVisible=false">取消</el-button>
  </el-form-item>
    </el-form>
    </el-dialog>
      </div>
  </template>
  
  <script>
  let inputElement = null
export default{
        data(){
          return{
            formInline:{},
            empList:[],
            dialogVisible:false,
            form:{},
            tishi:"",
            path:"http://localhost:8080/",
            valueUrl: '',
			ff:{},
            currentPage: 1,
            currentSize:5,
            AllData:0,
            deptList:[],
          }
        },
        filters: {
            dateFilter(val){
              let date = new Date(val);
              return date.getFullYear()+"年"+(date.getMonth()+1)+"月"+(date.getDate())+"日"
            }
        },
        methods:{
          getList(){
           // console.log(this.path+"user/"+this.currentPage+"/"+this.currentSize);
            this.$axios.get(this.path+"emp/"+this.currentPage+"/"+this.currentSize).then(res=>{
              this.empList=res.data.data.pageInfo.list;
              this.AllData = res.data.data.pageInfo.total;
              this.deptList =res.data.data.deptList;
            });
          },
          sureSubmit(){
            console.log(this.formInline.empName);
            console.log(this.formInline.deptId);
            let formData = new FormData();
            formData.append("empName",this.formInline.empName);
            formData.append("deptId",this.formInline.deptId);
            if(this.formInline.time){
              let date = new Date(this.formInline.time[0]);
              let date1 = new Date(this.formInline.time[0]);
            formData.append("beginTime",date.getFullYear()+"/"+date.getMonth()+1+"/"+date.getDate());
            formData.append("endTime",date1.getFullYear()+"/"+date1.getMonth()+1+"/"+date1.getDate());
            }
            this.$axios.post(this.path+"emp/other",formData ).then(res=>{
              this.empList=res.data.data.list;
              this.AllData = res.data.data.total;
            })
          },
          handleSizeChange(val) {
              this.currentSize=val;
              //console.log(`每页 ${val} 条`);
              this.getList();
          },
          handleCurrentChange(val) {
            this.currentPage=val;
           // console.log(`当前页: ${val}`);
            this.getList();
          },
          open(){
            this.tishi="添加"
            this.form={};
            this.valueUrl='' ;
            this.ff={};              
            this.dialogVisible=true;
          },
          onSubmit(){
            if(this.form.id==null){
             this.form.salary==null?this.form.salary=0:this.form.salary
             let formDate = new  FormData();
             formDate.append("name",this.form.name);
             formDate.append("salary",this.form.salary);
             formDate.append("age",this.form.age);
             formDate.append("entryDate",this.form.entryDate);
             formDate.append("deptId",this.form.deptId);
             formDate.append("photoFile",this.ff);
            this.$axios.post(this.path+"emp",formDate).then(res=>{
              if(res.data.code==200){
                this.dialogVisible=false;
                this.$message.success(res.data.msg);
                this.form={};
 /*                 if(this.$refs.file){
                   this.$refs.file.value='';
                 } */
                 this.file={};
                 this.valueUrl='';
                this.getList();
                }else{
                  this.file={};
                  this.valueUrl='';
                  this.dialogVisible=false;
                  this.$message.error(res.data.msg);
                }
              });
            }else{
              let formDate = new  FormData();
              this.form.salary==null?this.form.salary=0:this.form.salary
              formDate.append("id",this.form.id);
              formDate.append("name",this.form.name);
             formDate.append("salary",this.form.salary);
             formDate.append("age",this.form.age);
             formDate.append("entryDate",this.form.entryDate);
             formDate.append("deptId",this.form.deptId);
             formDate.append("photo",this.form.photo);
             formDate.append("photoFile",this.ff);
              this.$axios.put(this.path+"emp",formDate).then(res=>{
              if(res.data.code==200){
                this.dialogVisible=false;
                this.$message.success(res.data.msg);
                this.form={};
                this.file={};
                this.valueUrl='';
                this.getList();
                }else{
                  this.dialogVisible=false;
                  this.$message.error(res.data.msg);
                }
              });
            }
          },
          handleEdit(u){
            this.tishi="修改"
            this.ff={};
            this.valueUrl=this.path+"imgs/"+u.photo;
            let date = new Date(u.entryDate);

            u.entryDate= date.getFullYear()+"/"+(date.getMonth()+1)+"/"+date.getDate();

            let userJson = JSON.stringify(u);            
            this.form=JSON.parse(userJson);
            this.dialogVisible=true;
          },
          handleDelete(id){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
          this.$axios.delete(this.path+"emp/"+id).then(res=>{
              if(res.data.code==200){
                this.dialogVisible=false;
                this.$message.success(res.data.msg);
                this.getList();
                }else{
                  this.dialogVisible=false;
                  this.$message.error(res.data.msg);
                }
            });
            }).catch(() => {
              this.$message({
              type: 'success',
              message: '取消删除'
            });          
          }); 
      },
      toGetImg() {
				if (inputElement === null) {
				// 生成文件上传的控件
					inputElement = document.createElement('input')
					inputElement.setAttribute('type', 'file')
					inputElement.style.display = 'none'
					if (window.addEventListener) {
						inputElement.addEventListener('change', this.uploadFile, false)
					} else {
						inputElement.attachEvent('onchange', this.uploadFile)
					}
					document.body.appendChild(inputElement)
				}
				inputElement.click()
			},
			uploadFile(el) {
				if (el && el.target && el.target.files && el.target.files.length > 0) {
					//console.log(el)
					const files = el.target.files[0]
					const isLt2M = files.size / 1024 / 1024 < 2
					const size = files.size / 1024 / 1024
					//console.log(size)
					// 判断上传文件的大小
					if (!isLt2M) {
						this.$message.error('上传头像图片大小不能超过 2MB!')
					} else if (files.type.indexOf('image') === -1) { //如果不是图片格式
						// this.$dialog.toast({ mes: '请选择图片文件' });
						this.$message.error('请选择图片文件');
					} else {	
						const that = this;
						const reader = new FileReader(); // 创建读取文件对象
						reader.readAsDataURL(el.target.files[0]); // 发起异步请求，读取文件
						reader.onload = function() { // 文件读取完成后
							// 读取完成后，将结果赋值给img的src
							that.valueUrl = this.result;
							//console.log(this.result);
							// 数据传到后台
							//console.log(that.valueUrl);
							//console.log(files);
						//const formData = new FormData()
						//formData.append('photoData', files); // 可以传到后台的数据
							that.ff=files;
						};
					}
				}
			}
      },
        mounted(){
          this.getList();
        }
      }
  </script>
  <style scoped>
  .footer{
    width:100%;
    text-align: center;
    position:fixed;
    bottom:40px;
  }
.alert-box-item {
		overflow: hidden;
	}

	.bigImg-div {
		width: 150px;
		height: 150px;

		overflow: hidden;
		border: 1px solid #ddd;
	}

	.bigImg {
		display: block;
		width: 150px;
		height: 150px;
		
	}
</style>